package com.demo.meituan;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LeafSegmentIDGenerator {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/leaf";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "password";

    public static long generateID(String bizTag) {
        long id = -1;
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            connection.setAutoCommit(false);
            String query = "SELECT max_id, step FROM leaf_alloc WHERE biz_tag = ?";
            PreparedStatement selectStmt = connection.prepareStatement(query);
            selectStmt.setString(1, bizTag);

            ResultSet resultSet = selectStmt.executeQuery();
            if (resultSet.next()) {
                long maxId = resultSet.getLong("max_id");
                int step = resultSet.getInt("step");
                id = maxId + 1;

                // Update max_id in the database
                String updateQuery = "UPDATE leaf_alloc SET max_id = max_id + ? WHERE biz_tag = ?";
                PreparedStatement updateStmt = connection.prepareStatement(updateQuery);
                updateStmt.setInt(1, step);
                updateStmt.setString(2, bizTag);
                updateStmt.executeUpdate();
            }

            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public static void main(String[] args) {
        String bizTag = "order_id";
        System.out.println("Generated ID: " + generateID(bizTag));
    }
}
